文件描述符
- 0 : STDIN_FILENO
- 1 : STDOUT_FILENO
- 2 : STDERR_FILENO
- 范围: 0 ~ OPEN_MAX -1
open and openat
1234#include <fcntl.h>int open(const char *path, int oflag, ... /* mode_t mode */ );int openat(int fd, const char *path, int oflag, ... /* mode_t mode */ );Both return: file descriptor if OK, −1 on error- open 和 openat 函数返回当前未用最小文件描述符数值
- path specifies an absolute path, then
open
equals toopenat
- path specifier an relative path, The
fd
parameter is obtained by opening the directory by the relative pathname
creat
123#include<fcntl.h>int creat (const char *path, mode_t mode);Returns: file descriptor opened for write-only if OK, −1 on error
open(path, O_RDWR | O_CREAT | O_TRUNC, mode);
close
123#include <unistd.h>int close(int fd);Returns: 0 if OK, −1 on errorlseek
123#include <fcntl.h>off_t lseek(int fd, off_t offset, int whence);returns: offset if ok, -1 on error
• If whence is SEEK_SET, the file’s offset is set to offset bytes from the beginning of
the file.
• If whence is SEEK_CUR, the file’s offset is set to its current value plus the offset.
The offset can be positive or negative.
• If whence is SEEK_END, the file’s offset is set to the size of the file plus the offset.
The offset can be positive or negative.
- read/write12345#include <unistd.h>ssize_t read(int fd, void *buf, size_t nbytes);$ Returns: number of bytes read, 0 if end of file, −1 on errorssize_t write(int fd, const void *buf, size_t nbytes);$ Returns: number of bytes written if OK, −1 on error
文件共享
文件打开后
- 每个进程在进程变种有一个记录项,记录项包含一张文件描述符表(当前进程打开的所有文件)每个文件描述符包含:一个文件描述符标志,一个指向文件表项的指针
- 内核为所有打开文件维持一张文件表,每个表项包含:文件状态,当前文件偏移,该文件的v节点表项指针
- 每个打开文件都有一个v节点.包含:文件类型,文件操作指针,索引节点等
- 每个进程都有自己的文件表项为了维持不同的当前文件偏移量
原子操作
- 追加:每次都定位到结尾并写入:
定位结尾
与写入
整合为一个原子操作 pread/pwrite
12345#include <unistd.h>ssize_t pread(int fd, void *buf, size_t nbytes, off_t offset);Returns: number of bytes read, 0 if end of file, −1 on errorssize_t pwrite(int fd, const void *buf, size_t nbytes, off_t offset);Returns: number of bytes written if OK, −1 on error定位
与读写
操作为一个整体不可中断
- 不更新当前文件偏移量
- 创建文件:
检测当前文件是否存在
与创建文件
整合为一个操作
dup/dup2
1234#include <unistd.h>int dup(int fd);int dup2(int fd, int fd2);Both return: new file descriptor if OK, −1 on errordup
返回当前最小可用文件描述符
dup2
关闭fd2
,若fd == fd2
不关闭直接返回fd2
函数sync
,fsync
和fdatasync
12345 #include <unistd.h>int fsync(int fd);int fdatasync(int fd);Returns: 0 if OK, −1 on errorvoid sync(void);
sync
修改过区块排入写队列.update
守护进程周期性调用flush
缓冲区fsync
只对fd
文件作用,并等待文件写完
fdatasync
只影响数据部分,同步更新文件属性
函数ioctl
123456 > #include <unistd.h>#include <sys/ioctl.h>/* System V *//* BSD and Linux */int ioctl(int fd, int request, ...);Returns: −1 on error, something else if OK
习题/思维导图